<?php

declare(strict_types=1);

namespace app\agent\controller\channel;

use app\agent\controller\Controller;
use app\api\service\OilStoreService;
use app\model\OilAgentChannel as Model;
use think\Request;

class Oil extends Controller
{
    /**
     * @api {GET} /agent/channel.oil/ 代理商列表
     * @apiName 代理商列表
     * @apiGroup oilAgent
     * @apiParam {String} [name] 代理商名称
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function index(Request $request)
    {
        $where = [['agent_id', '=', $this->agent['id']]];
        if ($request->param('name', '')) {
            $where[] = ['name', 'like', '%'.$request->param('name').'%'];
        }

        $oilStoreService = invoke(OilStoreService::class);

        $list = Model::where($where)->withSum(['order' => function ($query) {
            $query->where('status', 1)->where('refund_status', 0);
        }], 'pay_amount')
            ->withCount(['order' => function ($query) {
                $query->where('status', 1)->where('refund_status', 0);
            }])
            ->paginate($request->only(['page' => 1, 'list_rows' => 15]))
            ->toArray();

        foreach ($list['data'] as $k => $v) {
            $urlData = $oilStoreService->makeH5Url($v['id']);
            $list['data'][$k]['url'] = $urlData['data']['h5'];
        }

        return success('操作成功', $list);
    }

    /**
     * @api {POST} /agent/channel.oil/save 新建或者保存
     * @apiName 代理商信息保存
     * @apiGroup oilAgent
     * @apiParam {Number} [id] id 更新时候传递
     * @apiParam {String} name 名称
     * @apiParam {String} status 状态
     * @apiParam {String} memo  描述
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function save(Request $request)
    {
        $rules = [
            'name' => 'require',
            'status' => 'require',
            'memo' => 'require',
        ];
        $messages = [
            'name.require' => '请输入渠道名称',
            'memo.require' => '请输入渠道描述',
            'status.require' => '请勾选',
        ];
        $param = $request->only(['name', 'status', 'memo']);
        $id = $request->param('id', 0);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        $param['agent_id'] = $this->agent['id'];
        $where = [['agent_id', '=', $param['agent_id']], ['name', '=', $param['name']]];
        if ($id) {
            $where[] = ['id', '<>', $id];
        }

        // 名称校验
        if ($existData = Model::where($where)->find()) {
            return fail('渠道名称和id='.$existData['id'].'的渠道冲突了');
        }
        if ($id) {
            $oilAgentChannel = Model::find($id);
        } else {
            $oilAgentChannel = new Model();
        }

        if ($oilAgentChannel->save($param)) {
            return success();
        } else {
            return fail();
        }
    }

    /**
     * @api {GET} /agent/channel.oil/read 代理商详细
     * @apiName 代理商详细
     * @apiGroup oilAgent
     * @apiParam {Number} id id
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function read(Request $request)
    {
        if (!$id = $request->param('id', 0)) {
            return fail('缺少必要参数');
        }
        $data = Model::where('agent_id', $this->agent['id'])->find($id);

        if ($data) {
            return success('', $data->toArray());
        } else {
            return fail('数据不存在');
        }
    }

    /**
     * @api {POST} /agent/channel.oil/delete 代理商删除
     * @apiName 代理商删除
     * @apiGroup oilAgent
     * @apiParam {Number} id id
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function delete(Request $request)
    {
        if (!$id = $request->param('id', 0)) {
            return fail('缺少必要参数');
        }
        $orderCount = \think\facade\Db::name('oil_order')
            ->where('agent_id', $this->agent['id'])
            ->where('cnid', $id)
            ->count();
        if ($orderCount) {
            return fail('该渠道有产生订单，无法删除');
        }
        $channel = Model::where('id', $id)->where('agent_id', $this->agent['id'])->find();
        if (!$channel || $channel->delete()) {
            return success('删除成功');
        } else {
            return fail();
        }
    }
}
